package com.lxs.common.exception;

import com.lxs.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
@Slf4j
@RestControllerAdvice
public class ExceptionControllerAdvice {
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handlerValidException(MethodArgumentNotValidException e){
        HashMap map = new HashMap();
        e.getFieldErrors().forEach((fieldError)->{
            String field= fieldError.getField();
            String msg=fieldError.getDefaultMessage();
            map.put(field,msg);
        });
        return R.error(BizCodeEnum.VALID_EXCEPTION.getCode(),BizCodeEnum.VALID_EXCEPTION.getMsg()).put("data",map);
    }
    @ExceptionHandler(value=Throwable.class)
    public R handException(Throwable throwable){
        log.error("错误信息：",throwable);
        return R.error(BizCodeEnum.UNKNOWN_EXCEPTION.getCode(),BizCodeEnum.UNKNOWN_EXCEPTION.getMsg()).put("data", throwable.getMessage());
    }
}
